﻿Ext.define('SmartClient.controller.ProductsController',
   {
      extend: 'Deft.mvc.ViewController',
      inject: ['productsStore', 'ordersStore'],

      init: function ()
      {
         var me = this;

         me.getProductsStore().addListener('load', this.fillData, this);
         me.getProductsStore().load();
         me.getViewAddedProductsButton().setText('Added products (' + this.getAddedProductsAmount() + ')');
         me.getViewAddedProductsButton().setHandler(this.showAddedProducts, this);
         me.getViewOrdersHistoryButton().setHandler(this.showOrdersHistory, this);
         return me.callParent(arguments);
      },

      // Element IDs here
      // DeftJS will create a getter and setter for property
      control:
         {
            productsList: true,
            topToolbar: true,
            viewAddedProductsButton: true,
            viewOrdersHistoryButton: true
         },

      // Ext JS will create a getter and setter for property
      config:
         {
            productsStore: null,
            ordersStore: null
         },

      statics:
         {
            buttonsAdded: false,

            generateAddedProductFromTemplate: function (id, amount)
            {
               return '{id=' + id + ',orderedAmount=' + amount + '}';
            },
         },

      fillData: function (me, products, success)
      {
         var templateData = [];
         Ext.each(products, function (product, index)
         {
            templateData.push(product.data);
         });
         this.getProductsList().update(templateData);
         this.addButtons(this.getProductsList());
      },

      addButtons: function (productsList)
      {
         var me = this;

         if (productsList.data && productsList.data.length > 0)
         {
            Ext.each(productsList.data, function (product, index)
            {
               Ext.create('Ext.button.Button',
               {
                  text: 'Add to order',
                  renderTo: 'addToOrderButton' + (index + 1),
                  handler: function ()
                  {
                     me.addProductToOrder(product.id, product.availableAmount, product.units);
                  }
               });
            });
            this.adjustProductsListHeight();
         }
      },

      adjustProductsListHeight: function()
      {
         var topToolbarHeight = this.getView().getComponent('topToolbar').getHeight();
         this.getView().getComponent('productsList').setHeight(window.innerHeight - topToolbarHeight);
      },

      addProductToOrder: function (productId, availableAmount, units)
      {
         var me = this,
             vtype;
             addedProductsAmount = me.getAddedProductsAmount(productId),
             textFieldValue = addedProductsAmount > 0 ? addedProductsAmount : 1;
         
         if (units === me.self.PCS_UNITS)
         {
            vtype = Ext.form.field.VTypes.intName;
         }
         if (!Ext.getCmp('productsAmountPopup'))
         {
            Ext.create('SmartClient.view.ProductsAmountPopupView',
            {
               productId: productId,
               availableAmount: availableAmount,
               units: units,
               textFieldVtype: vtype,
               textFieldValue: textFieldValue
            }).show();
         }
      },

      refreshViewAddedProductsButtonText: function()
      {
         var addedProductsButtonText = this.getViewAddedProductsButton().getText();
         this.getViewAddedProductsButton().setText(addedProductsButtonText.replace(/\d+/, this.getAddedProductsAmount()));
      },
      
      getAddedProductsAmount: function (productID)
      {
         var addedProductsAmount;

         if (productID)
         {
            var addedProduct = this.findAddedProduct(productID);
            if (addedProduct)
            {
               addedProductsAmount = parseFloat(addedProduct[1]);
            }
            else
            {
               addedProductsAmount = 0;
            }
         }
         else
         {
            // Amount of all ordered products
            var orderedItems = SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.ADDED_PRODUCTS_COOKIE);
            addedProductsAmount = orderedItems.split('}').length - 1;
            if (addedProductsAmount == -1)
            {
               addedProductsAmount = 0;
            }
         }
         return addedProductsAmount;
      },

      findAddedProduct: function (productID)
      {
         return new RegExp("\\{id\\=" + productID + ",orderedAmount\\=(\\d+(?:\\.\\d+)?)\\}")
           .exec(SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.ADDED_PRODUCTS_COOKIE));
      },

      showAddedProducts: function ()
      {
         var addedProducts = SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.ADDED_PRODUCTS_COOKIE),
             me = this;

         if (addedProducts)
         {
            var products = [],
                addedProducts = addedProducts.split(SmartClient.Application.ADDED_PRODUCTS_DELIMITER);
            Ext.each(addedProducts, function (addedProduct, index)
            {
               var product = /{id=(\d+),orderedAmount=(\d+(?:\.\d+)?)}/.exec(addedProduct),
                   id = product[1],
                   orderedAmount = product[2],
                   product = Ext.clone(me.productsStore.findRecord('id', id).data);
               
               product.orderedAmount = orderedAmount;
               products.push(product);
            });

            if (products.length > 0)
            {
               var productsStore = Ext.create('SmartClient.store.ProductsStore',
                   {
                      data: products
                   });
               if (!Ext.getCmp('addedProductsWindow'))
               {
                  Ext.create('SmartClient.view.AddedProductsView',
                     {
                        store: productsStore,
                        orderId: SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.EDITED_ORDER_COOKIE)
                     }).show();
               }
            }
         }
      },

      updateProductAmount: function (productId, productAmount)
      {
         var addedProduct = this.findAddedProduct(productId)[0],
             addedProductWithNewAmount = this.self.generateAddedProductFromTemplate(productId, productAmount),
             allProducts = SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.ADDED_PRODUCTS_COOKIE);

         SmartClient.utils.CookieUtils.setCookie(SmartClient.Application.ADDED_PRODUCTS_COOKIE,
            allProducts.replace(addedProduct, addedProductWithNewAmount));
      },

      showOrdersHistory: function ()
      {
         var ordersStore = this.getOrdersStore();
         ordersStore.load(function (records, operation, success)
         {
            Ext.create('SmartClient.view.OrdersHistoryView',
                  {
                     store: ordersStore
                  }).show();
         });
      }
});